package com.road2trip.gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.road2trip.gwt.client.tools.JSONRequestHelper;
import com.road2trip.gwt.client.tools.JSONRequestHelper.JSONResponseHandler;

/**
 * 
 * Oracle for "search" suggestbox. Make a request to google maps HTTP API.    
 *
 */
public class MapSuggestOracle extends SuggestOracle {

    public boolean isDisplayStringHTML() {
        return true;
    }

    public void requestSuggestions(SuggestOracle.Request req, SuggestOracle.Callback callback) {
        
    	String url = "http://maps.google.com/maps/geo?output=json&oe=utf8&sensor=false";
        url += "&hl=en"; 
        //@TODO : google api KEY 
        //url += "&key=YOUR_GOOGLE_MAPS_API_KEY";
        url += "&q=" + req.getQuery();
    	GWT.log("requestSuggestion : " + url, null);
    	JSONRequestAdaptor rp = new JSONRequestAdaptor(req, callback); 
    	rp.get(url);
    }
    
    
    public class SimpleSuggestion implements Suggestion {
        private String s;
        public SimpleSuggestion(String s) {
           this.s = s;
        }
        public String getDisplayString() {
            return s;
        }
        public String getReplacementString() {
            return s;
        }
    }
    
    /**
     * Inner adaptor class to call the REST service and adapt it to the SuggestOracle  
     */
    class JSONRequestAdaptor {
    	
    	private SuggestOracle.Request req;
        private SuggestOracle.Callback callback;
        
        public JSONRequestAdaptor(SuggestOracle.Request _req,  SuggestOracle.Callback _callback) {
            req = _req;
            callback = _callback;
        }
        
        public void get(String url){
        	JSONRequestHelper.get(url, new JSONResponseHandler() {			
    			@Override
    			public void onResponseReceived(JavaScriptObject json) {
    				JSONObject jsonObject = new JSONObject(json);
    		    	GWT.log("onResponseReceived : " + jsonObject.toString(), null);    				
    				JSONArray ary = jsonObject.get("Placemark").isArray();
    				java.util.ArrayList<SimpleSuggestion> suggestions = new java.util.ArrayList<SimpleSuggestion>();
    			    for (int i = 0; i < ary.size(); ++i) {
    			    	String str = ary.get(i).isObject().get("address").isString().stringValue(); 
    			    	int accuracy = (int)ary.get(i).isObject().get("AddressDetails").isObject().get("Accuracy").isNumber().doubleValue();
    			    	GWT.log("adress :" + str + " - " + accuracy, null);
    			    	if (accuracy >= 1 && accuracy <= 4){  
    			    		// between country and town. See : http://code.google.com/apis/maps/documentation/geocoding/index.html#GeocodingAccuracy
    			    		SimpleSuggestion s = new SimpleSuggestion(str);
	    			    	suggestions.add(s);
	    			    	GWT.log("suggestion: " + s.getDisplayString(), null);
    			    	}	    			        			
      				}    			        			    
    			    callback.onSuggestionsReady(req, new SuggestOracle.Response(suggestions) );    			    
    			}
    		});     
        }
              
    }
    
}